from flask import Flask, get_flashed_messages
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
import logging
from logging.handlers import RotatingFileHandler
from flask_session import Session
from .config import Config

db = SQLAlchemy()
csrf = CSRFProtect()

# 配置日志
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
rotating_handler = RotatingFileHandler(filename="logs/log.txt", maxBytes=1024*1024, backupCount=10)
logging.getLogger().addHandler(rotating_handler)

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    # csrf token验证
    csrf.init_app(app)

    # 初始化session
    Session(app)

    # 初始化会话
    db.init_app(app)

    with app.app_context():
        from app.models import Admin, Article, Tag, Link, Category

        # db.drop_all()
        # db.create_all()
        # from app.test_data import init_data
        # init_data(db)

    # 注册蓝图
    from app.controller import register_blueprint
    register_blueprint(app)

    @app.errorhandler(404)
    def page_not_find(e = None):
        return "404"
    
    @app.errorhandler(500)
    def page_error(e=None):
        return "".join(get_flashed_messages())
        
    return app